<template>
  <div class="about">
    <h1>
      <van-button type="primary" @click="toggleCamera">切换摄像头</van-button>
      <van-button type="primary" @click="closeCamera">关闭摄像头</van-button>
      <van-button type="primary" @click="openCamera">开启摄像头</van-button>
      <van-button type="primary" @click="changeResolution('720P')">720P</van-button>
      <van-button type="primary" @click="changeResolution('1080P')">1080P</van-button>
      <van-button type="primary" @click="changeResolution('2K')">2K</van-button>
    </h1>
    <video playsinline style="width:100%;height: auto;transform: scaleX(-1)" ref="video" autoplay></video>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
const video = ref(null)
const cameraConfig = ref({
  audio: false,
  video: {
    frameRate: { min: 24 },
    width: { ideal: 1280 },
    height: { ideal: 720 },
    facingMode: 'user', // 'user'
  }
})
const resolution = {
  '720P': { width: 1280, height: 720 },
  '1080P': { width: 1920, height: 1080 },
  '2K': { width: 2560, height: 1440 }
}

const closeCamera = () => {
  if (video.value.srcObject) {
    video.value.srcObject.getTracks().forEach(track => track.stop())
    video.value.srcObject = null
  }
}

const startCamera = async () => {
  try {
    if (video.value.srcObject) {
      video.value.srcObject.getTracks().forEach(track => track.stop())
      // video.value.srcObject = null
    }
    const stream = await getStream()
    if (stream) {
      video.value.pause() // Pause the video before setting srcObject
      video.value.srcObject = stream
      video.value.load()
      video.value.play() && video.value.play().then(() => {
        console.debug('开始播放')
      }).catch(error => {
        console.error('Error playing video:', error)
        alert(`Error playing video: ${error.message}`)
      })
    }
  } catch (error) {
    console.error('Error starting camera:', error)
    alert(`Error starting camera: ${error.message}`)
  }
}

const changeResolution = async (type) => {
  cameraConfig.value.video.width = resolution[type].width
  cameraConfig.value.video.height = resolution[type].height
  await startCamera()
}

const toggleCamera = async () => {
  cameraConfig.value.video.facingMode = cameraConfig.value.video.facingMode === 'user' ? 'environment' : 'user'
  await startCamera()
}

const openCamera = async () => {
  await startCamera()
}

const getStream = async () => {
  if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
    alert('Your browser does not support getUserMedia API')
    return null
  }

  try {
    return await navigator.mediaDevices.getUserMedia(cameraConfig.value)
  } catch (error) {
    console.error('Error accessing camera:', error)
    alert(`Error accessing camera: ${error.message}`)
    return null
  }
}

onMounted(() => {
  openCamera()
})
</script>

<style>
@media (min-width: 1024px) {
  .about {
    min-height: 100vh;
    display: flex;
    align-items: center;
  }
}
</style>
